import cv2 as cv
import sys
import os
from python_ai.common.xcommon import *
import matplotlib.pyplot as plt
import numpy as np
import time
import datetime

pic_dir = '../../../../../large_data/pic/'
# pic = os.path.join(pic_dir, 'messi_large.jpg')
# pic = os.path.join(pic_dir, 'messi5.jpg')
pic = os.path.join(pic_dir, 'IMG_20200819_124310.jpg')
# pic_dir = '../../../../../large_data/pic/fruit'
# pic = os.path.join(pic_dir, 'orange.jpeg')
A = cv.imread(pic, cv.IMREAD_COLOR)
A_shape = A.shape
H = A_shape[0]
W = A_shape[1]
rate = 750. / W
A = cv.resize(A, None, fx=rate, fy=rate, interpolation=cv.INTER_CUBIC)
# A = cv.blur(A, (5, 5))
A_shape = A.shape
H = A_shape[0]
W = A_shape[1]
H2 = H // 2
W2 = W // 2
print(f'H {H}, W {W}')
print(f'H2 {H2}, W2 {W2}')
img_gray = cv.cvtColor(A, cv.COLOR_BGR2GRAY)
ret, thresh = cv.threshold(img_gray, 127, 255, cv.THRESH_BINARY)
contours, hierarchy = cv.findContours(thresh, cv.RETR_EXTERNAL, cv.CHAIN_APPROX_SIMPLE)
sep(f'contours.len = {len(contours)}')
A_copy = A.copy()
cv.drawContours(A_copy, contours, -1, (0, 255, 0), 2)
bg = np.zeros_like(A_copy)
max_area = 0
i_max = 0
for i, con in enumerate(contours):
    con_area = cv.contourArea(con)
    if con_area > max_area:
        max_area = con_area
        i_max = i
print(f'Max i: {i}')
cv.drawContours(bg, contours, i_max, (0, 255, 0), 2)

# moments
cnt = contours[i_max]
M = cv.moments(cnt)
print(M)
cx = int(M['m10'] / M['m00'])
cy = int(M['m01'] / M['m00'])
print(f'center: {cx}, {cy}')
cv.circle(bg, (cx, cy), 5, (0, 0, 255), 2)
area = cv.contourArea(cnt)  # ATTENTION api contourArea
print(f'area: {area}')

# concatenate
row01 = np.concatenate((img_gray, thresh), axis=1)
row01 = cv.cvtColor(row01, cv.COLOR_GRAY2BGR)
row02 = np.concatenate((A_copy, bg), axis=1)
img_all = np.concatenate((row01, row02), axis=0)
cv.line(img_all, (W, 0), (W, 2 * H), (0, 0, 255), 1)
cv.line(img_all, (0, H), (2 * W, H), (0, 0, 255), 1)

cv.imshow('contours', img_all)
cv.waitKey(0)
